package small.woods.msweb.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import small.woods.msweb.intergration.TestIntergration;
import small.woods.msweb.model.bo.LoginForm;
import small.woods.msweb.model.enums.RespondCodeEnum;
import small.woods.msweb.service.UserService;
import small.woods.msweb.utils.RespondResult;

/**
 * @Author: small_woods
 * @Date: 2020/6/16 11:49
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(description = "用户")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private TestIntergration testIntergration;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public String login(@RequestBody LoginForm loginForm){
        String userName = loginForm.getUserName();
        String password = loginForm.getPassword();
        if(password.equals(userService.selectByUserName(userName))){
            System.out.println("登录成功！");
        }else{
            System.out.println("失败");
            RespondResult.error(RespondCodeEnum.userNameAndPasswordError);
        }

        return null;
    }

    @ApiOperation(value = "用户测试")
    @GetMapping("/test")
    public String test(){
        testIntergration.test();
        return "ok";
    }

    //通过HystrixCommand注解，手动指定一个降级方法，出现异常后会调用该降级方法
    @ApiOperation(value = "获取用户名")
    @GetMapping("/getName")
    @HystrixCommand(fallbackMethod = "getNameFallback")
    public String getName(@RequestParam("username") String username) throws Exception{
        if(username.equals("hello")){
            return "this is hello";
        }else{
            throw new Exception();
        }
    }

    /**
     * 出错后会调用该降级方法，返回指定的信息
     * @param username
     * @return
     */
    public String getNameFallback(String username){
        return " this username is not exist ";
    }
}
